<script setup>
import { Plus, Upload } from '@element-plus/icons-vue'
import {ref} from 'vue'
import avatar from '@/assets/avatar.jpg'
const uploadRef = ref()
import {userInfoStore} from "@/store/userInfoStore.js";
import {userTokenStore} from "@/store/userTokenStore.js";
import {ElMessage} from "element-plus";
import {UserAvatarService} from "@/api/user.js";
//用户头像地址
const InfoStore = userInfoStore();
const TokenStore = userTokenStore();
const imgUrl= ref(InfoStore.info.user_pic);
//笔记上传成功与否
const FileUpload = (result) => {
  imgUrl.value = result.data;
  print(imgUrl.value)
  console.log(result.data);
  console.log("上传成功");
  ElMessage.success("上传成功！");
};
const handleUploadError = (error) => {
  console.log(error);
  console.log("上传失败");
  ElMessage.error("上传失败");
};
const UpdateAvatarForUser = async ()=>{
  await UserAvatarService(imgUrl.value);
  ElMessage.success("修改成功!");
  InfoStore.info.userPic = imgUrl.value;
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>更换头像</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            :show-file-list="false"
            :headers = "{'Authorization':TokenStore.token}"
            action="/api/file/upload"
            name="file"
            :on-success="FileUpload"
            :on-error="handleUploadError"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" alt="图片" />
          <img v-else :src="avatar" width="278" alt="无图片"/>
        </el-upload>
        <br />
        <el-button type="primary" :icon="Plus" size="large"  @click="uploadRef.$el.querySelector('input').click()">
          选择图片
        </el-button>
        <el-button type="success" :icon="Upload" size="large" @click="UpdateAvatarForUser">
          上传头像
        </el-button>
      </el-col>
    </el-row>
  </el-card>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>